package org.jinyan.db.utils;

import java.util.Map;

public class MysqlBuilder {

	public static String buildAddSql(String tableName, Map data) {
		if (data.isEmpty()) {
			return null;
		}
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("INSERT INTO " + tableName + " (");
		Object setArray[] = data.keySet().toArray();
		for (int i = 0; i < setArray.length; i++) {
			Object key = setArray[i];
			if (i != 0) {
				sqlBuffer.append(",");
			}
			sqlBuffer.append(key);
		}
		sqlBuffer.append(") VALUES(");
		for (int i = 0; i < setArray.length; i++) {
			Object key = setArray[i];
			String val = data.get(key) + "";
			if (i != 0) {
				sqlBuffer.append(",");
			}
			sqlBuffer.append("'").append(val).append("'");
		}
		sqlBuffer.append(")");
		return sqlBuffer.toString();
	}

	public static String buildUpdateSql(String tableName, Map data,
			String pkAndValue) {
		if (data.isEmpty()) {
			return null;
		}
		StringBuffer sqlBuffer = new StringBuffer();
		Object setArray[] = data.keySet().toArray();
		sqlBuffer.append("UPDATE " + tableName + " SET ");
		for (int i = 0; i < setArray.length; i++) {
			Object key = setArray[i];
			String val = data.get(key) + "";
			if (i != 0) {
				sqlBuffer.append(",");
			}
			sqlBuffer.append(key + "='" + val+"'");
		}
		sqlBuffer.append(" WHERE " + pkAndValue);
		return sqlBuffer.toString();
	}

	public static String buildSelectSql(String tableName, Map data) {
		if (data.isEmpty()) {
			return null;
		}
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("SELECT * FROM " + tableName + " WHERE ");
		Object setArray[] = data.keySet().toArray();
		for (int i = 0; i < setArray.length; i++) {
			Object key = setArray[i];
			String val = data.get(key) + "";
			if (i != 0) {
				sqlBuffer.append(" AND ");
			}
			sqlBuffer.append(key + "='" + val+"'");
		}
		return sqlBuffer.toString();
	}

	public static String buildDeleteSql(String tableName, Map data) {
		if (data.isEmpty()) {
			return null;
		}
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("DELETE FROM " + tableName + " WHERE ");
		Object setArray[] = data.keySet().toArray();
		for (int i = 0; i < setArray.length; i++) {
			Object key = setArray[i];
			String val = data.get(key) + "";
			if (i != 0) {
				sqlBuffer.append(" AND ");
			}
			sqlBuffer.append(key + "='" + val+"'");
		}
		return sqlBuffer.toString();
	}

}
